home *** CD-ROM | disk | FTP | other *** search
- Path: news.th-darmstadt.de!news
- From: Enno Sandner <enno@intellektik.informatik.th-darmstadt.de>
- Newsgroups: comp.lang.c++
- Subject: Re: casting w/ virtual base classes
- Date: Tue, 16 Apr 1996 14:47:41 +0200
- Organization: Fachbereich Informatik, TH Darmstadt
- Message-ID: <317396ED.ABD322C@intellektik.informatik.th-darmstadt.de>
- References: <31728499.6201DD56@unisql.com>
- NNTP-Posting-Host: kitz.intellektik.informatik.th-darmstadt.de
- Mime-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- X-Mailer: Mozilla 2.01 (X11; I; SunOS 4.1.3 sun4m)
-
- Ed Hill wrote:
- >
- > I have the following class hierarchy
- >
- > class Derived : public virtual Base {...};
- >
- > Suppose there is a function foo that returns a pointer to a virtual
- > base class.
- >
- > Base* foo(void) {...}
- >
- > Now, in my program I have a variable declared as a pointer to Derived.
- >
- > int main() {
- > Derived *dp;
- > ...
- > exit 0;
- > }
- >
- > Book Explanation:
- > =================
- > In a virtual derivation, the derived class object contains the derived
- > part and a pointer to the virtual base part. The virtual base class is
- > not contained within the derived class object.
- > ==================
- >
- > My compiler does not allow either of the two following statements:
- >
- > Derived *dp1 = foo();
- > Derived *dp2 = (Derived *) foo();
- >
- > error: cast: Base* ->derived dp2*; Base is virtual base
- >
- > Ok, fine...
- >
- > However, the following compiles:
- >
- > Derived *dp = (Derived *) (void *) foo();
- >
- > Then, I'm able to access members of Derived and get correct data,
- > remember foo() returns a pointer to a virtual base.
- >
- > dp->num; // for example
- >
- > ===
- > Q1: Is the double cast legal? Why? / Why not?
-
- It's legal -- but the result is undefined.
- The forthcoming C++ standard provides a special cast-operator
- for this purpose. The 'dynamic_cast'
-
- Derived* dp=dyanmic_cast<Derived*>(foo());
-
- will safely narrow the pointer (*). If the returned object
- is not an object of a subclass of 'Dervived', the dynamic_cast
- expression returns a null-pointer.
-
- Enno
-
- (*) Base should have at least one virtual function, e.g. the dtor.
-